﻿using Lee.EF.Context;
using Lee.Models.Entities;
using Microsoft.EntityFrameworkCore;

namespace EFCoreApp;
/// <summary>
/// 乐观并发
/// builder.Property(x => x.Owner).IsConcurrencyToken();
/// </summary>
public class EF_optimistic
{
    public async Task optimisticTest(string _currOwner)
    {
        //string _currOwner = "test"; //Console.ReadLine();//当前用户
        using var ctx = new MyDBContext();
        var cop = await ctx.Set<Biz_Coupons>().SingleAsync(x => x.Id == 3);
        if (!string.IsNullOrEmpty(cop.Owner))
        {
            Console.WriteLine($"券被抢了");
        }
        else
        {
            //Thread.Sleep(500);
            await Task.Delay(1000);
            try
            {
                cop.Owner = _currOwner;
                await ctx.SaveChangesAsync();
                Console.WriteLine($"恭喜{_currOwner}抢到券{cop.Id}了");
            }
            catch (DbUpdateConcurrencyException ex)
            {
                var entry = ex.Entries.First();
                var dbValues = entry.GetDatabaseValues();
                var newOwner = dbValues.GetValue<string>(nameof(Biz_Coupons.Owner));
                Console.WriteLine($"并发冲突，{newOwner}已经抢到该券了");
            }
        }
        Console.WriteLine($"optimisticTest end");
    }
}